<template>
  <el-card>
    <el-form
      ref="infoForm"
      :model="formValidate"
      :rules="ruleValidate"
      label-width="undefined"
      @submit.prevent>
      <el-form-item prop="avatar">
        <el-avatar
          :size="100"
          :src="formValidate.avatar"
          style="cursor: pointer"
          @click="openAvatarUpload" />
      </el-form-item>
      <el-form-item :label="$t('forms.loginNo')" prop="loginNo">
        <span>{{ userInfo.loginNo }}</span>
      </el-form-item>
      <el-form-item :label="$t('lang')" prop="lang">
        <el-select-v2 v-model="currLang" :options="langList" @change="selectLang" />
      </el-form-item>
      <el-form-item :label="$t('forms.name')" prop="name">
        <el-input
          ref="name"
          v-model="formValidate.name"
          :disabled="modal_loading"
          :placeholder="$t('forms.pleaseEnter') + $t('forms.name')"
          type="text"
          @keyup.enter="handleSubmit" />
      </el-form-item>
      <el-form-item :label="$t('forms.mobile')" prop="mobile">
        <el-input
          v-model="formValidate.mobile"
          :disabled="modal_loading"
          :placeholder="$t('forms.pleaseEnter') + $t('forms.mobile')"
          type="text"
          @keyup.enter="handleSubmit" />
      </el-form-item>
      <el-form-item :label="$t('forms.changePassword')">
        <el-switch v-model="updatePassword" :disabled="modal_loading" />
      </el-form-item>
      <el-form-item
        v-show="updatePassword"
        :label="$t('forms.old') + $t('forms.password')"
        prop="oldPassword">
        <el-input
          v-model="formValidate.oldPassword"
          :disabled="modal_loading"
          :placeholder="$t('forms.pleaseEnter') + $t('forms.old') + $t('forms.password')"
          autocomplete="off"
          type="text"
          @focus="this.type = 'password'"
          @keyup.enter="handleSubmit" />
      </el-form-item>
      <el-form-item
        v-show="updatePassword"
        :label="$t('forms.new') + $t('forms.password')"
        prop="password">
        <el-input
          v-model="formValidate.password"
          :disabled="modal_loading"
          :placeholder="$t('forms.pleaseEnter') + $t('forms.new') + $t('forms.password')"
          :show-password="true"
          autocomplete="off"
          type="text"
          @focus="this.type = 'password'"
          @keyup.enter="handleSubmit" />
      </el-form-item>
      <el-form-item
        v-show="updatePassword"
        :label="$t('forms.confirmPassword')"
        prop="repeatPassword">
        <el-input
          v-model="formValidate.repeatPassword"
          :disabled="modal_loading"
          :placeholder="$t('forms.pleaseEnter') + $t('forms.new') + $t('forms.password')"
          :show-password="true"
          autocomplete="off"
          type="text"
          @focus="this.type = 'password'"
          @keyup.enter="handleSubmit" />
      </el-form-item>
      <el-form-item>
        <el-button :loading="modal_loading" type="default" @click="handleReset">
          {{ $t('forms.buttons.reset') }}
        </el-button>
        <el-button
          :loading="modal_loading"
          style="margin-left: 10px"
          type="primary"
          @click="handleSubmit">
          {{ $t('forms.buttons.submit') }}
        </el-button>
      </el-form-item>
    </el-form>
    <el-dialog v-model="avatarUpload" :fullscreen="true" :title="$t('forms.avatarUpload')">
      <cropper
        :src="avatarSrc"
        :crop-button-text="$t('el.messagebox.confirm')"
        @on-crop="handleCroped" />
      <el-backtop :visibility-height="10" target=".el-dialog" />
    </el-dialog>
  </el-card>
</template>
<script>
import avatarImg from '@/assets/images/avatar/avatar.jpg'
import Cropper from '@/components/cropper'
import { nextTick, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useAppStore } from '@/stores/app'

export default {
  name: 'personalInformation',
  components: {
    Cropper
  },
  data() {
    return {
      currLang: this.appStore.lang.lang,
      formValidate: {
        avatar: avatarImg,
        name: '',
        mobile: '',
        oldPassword: '',
        password: '',
        repeatPassword: ''
      },
      passwordComplexityPolicy: 0,
      updatePassword: false,
      avatarUpload: false,
      avatarSrc: '',
      modal_loading: false
    }
  },
  created() {
    this.resetFieldsValue(this.userInfo)
  },
  watch: {
    userInfo(newUserInfo) {
      this.resetFieldsValue(newUserInfo)
    }
  },
  computed: {
    langList() {
      return this.appStore.lang.langList
    },
    ruleValidate() {
      return {
        name: [
          {
            required: true,
            message: this.t('forms.name') + this.t('forms.notEmpty'),
            trigger: 'blur'
          }
        ],
        oldPassword: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.updatePassword) {
                if (value === '') {
                  callback(
                    new Error(
                      this.t('forms.old') + this.t('forms.password') + this.t('forms.notEmpty')
                    )
                  )
                  return
                }
              }
              callback()
            },
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.updatePassword) {
                if (value === '') {
                  callback(
                    new Error(
                      this.t('forms.new') + this.t('forms.password') + this.t('forms.notEmpty')
                    )
                  )
                  return
                }
                if (value.length < 8) {
                  callback(
                    new Error(
                      this.t('forms.new') +
                        this.t('forms.password') +
                        this.t('forms.lengthNotEnough') +
                        ' 8'
                    )
                  )
                  return
                }
                switch (this.passwordComplexityPolicy) {
                  case 1:
                    if (!/([a-zA-Z]+[0-9]+)|([0-9]+[a-zA-Z]+)/.test(value)) {
                      callback(
                        new Error(
                          this.t('forms.new') +
                            this.t('forms.password') +
                            this.t('forms.incorrectFormat')
                        )
                      )
                      return
                    }
                    break
                  case 2:
                    if (
                      !/([a-zA-Z]+[0-9]+)|([0-9]+[a-zA-Z]+)/.test(value) ||
                      !/[`~!@#$%^&*()+=|{}':;,\\"[\].<>]+/.test(value)
                    ) {
                      callback(
                        new Error(
                          this.t('forms.new') +
                            this.t('forms.password') +
                            this.t('forms.incorrectFormat')
                        )
                      )
                      return
                    }
                    break
                }
              }
              callback()
            },
            trigger: 'blur'
          }
        ],
        repeatPassword: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.updatePassword) {
                if (value === '') {
                  callback(new Error(this.t('forms.confirmPassword') + this.t('forms.notEmpty')))
                  return
                } else if (value !== this.formValidate.password) {
                  callback(new Error(this.t('forms.passwordNotEqual') + ''))
                  return
                }
              }
              callback()
            },
            trigger: 'blur'
          }
        ]
      }
    },
    userInfo() {
      return this.appStore.user.userInfo
    }
  },
  methods: {
    selectLang(name) {
      this.appStore.setLang(name)
    },
    openAvatarUpload() {
      this.avatarUpload = true
      nextTick(() => {
        this.avatarSrc = this.formValidate.avatar
      })
    },
    handleCroped(data) {
      this.avatarUpload = false
      this.formValidate.avatar = data
    },
    handleSubmit() {
      this.infoForm.validate((valid) => {
        if (valid) {
          this.modal_loading = true
          const userParam = {
            avatar: this.formValidate.avatar !== avatarImg ? this.formValidate.avatar : '',
            name: this.formValidate.name,
            mobile: this.formValidate.mobile
          }
          if (this.updatePassword) {
            userParam.oldPassword = this.formValidate.oldPassword
            userParam.password = this.formValidate.password
          }
          this.$api.request.auth
            .updateUserInfo(userParam)
            .then((res) => {
              this.appStore.setUserInfo(res.data)
              this.$message.success(this.t('messages.saveSuccess') + '')
              if (this.updatePassword) {
                this.$alert(this.t('messages.changedPassword') + '', this.t('dialog.info'), {
                  callback: () => {
                    this.modal_loading = false
                    this.$api.redirectLogin((callBackFunc) => {
                      this.$api.request.auth.doLogOut().then(() => {
                        callBackFunc()
                      })
                    })
                  }
                })
              } else {
                this.modal_loading = false
              }
            })
            .catch(() => {
              this.modal_loading = false
            })
        }
      })
    },
    handleReset() {
      this.infoForm.resetFields()
      this.resetFieldsValue(this.userInfo)
    },
    resetFieldsValue(userInfo) {
      if (userInfo.avatar && userInfo.avatar !== '') {
        this.formValidate.avatar = userInfo.avatar
      } else {
        this.formValidate.avatar = avatarImg
      }
      this.formValidate.name = userInfo.name
      this.formValidate.mobile = userInfo.mobile
    }
  },
  activated() {
    nextTick(() => {
      this.name.focus()
    })
    // 获取运行配置参数
    this.$api.request.runtime
      .getConfig(this.appStore.appInfo.passwordComplexityPolicy)
      .then((res) => {
        if (res && res.data && res.data.enabled) {
          this.passwordComplexityPolicy = parseInt(res.data.value)
        } else {
          this.passwordComplexityPolicy = 0
        }
      })
  },
  setup() {
    const infoForm = ref(null)
    const name = ref(null)
    const { t } = useI18n()
    const appStore = useAppStore()
    return { infoForm, name, t, appStore }
  }
}
</script>
